package 剑指offer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class p38字符串的排列 {

    List<String> resList=new ArrayList<>();
    public String[] permutation(String s) {
        if (s==null||s.length()==0) {
            return null;
        }
        char[] chars = s.toCharArray();
        Arrays.sort(chars);//排序后，将一样的字符放在一起方便后面进行剪枝
        StringBuilder minRes=new StringBuilder();
        boolean[] isVisted=new boolean[chars.length];
        backTrack(chars,isVisted,minRes);

        String[] res=new String[resList.size()];
        for (int i = 0; i <resList.size() ; i++) {
            res[i]=resList.get(i);
        }
        return res;
    }

    private void backTrack(char[] chars, boolean[] isVisted, StringBuilder minRes) {
        //递归出口
        if (minRes.length()==chars.length) {
            resList.add(minRes.toString());
            return;
        }

        //确定单层递归的逻辑
        for (int i = 0; i <chars.length ; i++) {
            if (isVisted[i]) {
                //访问过
                continue;
            }

            if (i!=0 && chars[i]==chars[i-1] && !isVisted[i-1]) {
                //剪枝：针对重复的字符不再回溯，两字符相等，并且前一个字符还没有访问(意思是：被访问过后修改回false)
                continue;
            }
            minRes.append(chars[i]);
            isVisted[i]=true;
            backTrack(chars,isVisted,minRes);

            //递归结束开始回溯
            minRes.deleteCharAt(minRes.length()-1);
            isVisted[i]=false;
        }
    }


    public static void main(String[] args) {
        List<List<Integer>> record=new ArrayList<>();
        List<Integer> path=new ArrayList<>();
        path.add(1);
        path.add(2);
        path.add(3);
        record.add(new ArrayList<>(path));

        path.clear();
        path.add(10);
        path.add(20);
        record.add(new ArrayList<>(path));

        record.toString();
        System.out.println(record);
    }
}
